<template>
  <a-card class="general-card" title="优惠券" :bordered="false">
    <a-tabs @change="(val)=>{apiParams.promotionStatus = val}" :default-active-key="couponStatus">
      <a-tab-pane key="NEW" title="未开始"></a-tab-pane>
      <a-tab-pane key="START" title="已开始"></a-tab-pane>
      <a-tab-pane key="END" title="已结束"></a-tab-pane>
      <a-tab-pane key="CLOSE" title="已关闭"></a-tab-pane>
    </a-tabs>
    <PickSearchColumn :columns="columnsSearch" time-type="timestamp" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}">
    </PickSearchColumn>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary" @click="add">
            添加
          </a-button>
          <a-button @click="delAll">
            批量关闭
          </a-button>
          <a-button type="primary" status="danger" @click="receivePage" style="margin: 5px">优惠券领取记录</a-button>
        </a-space>
      </a-col>
    </a-row>
    <PickTablePage ref="tablePageRef" :columns="columnsTable" :methods="sortMethods" :api="getShopCouponList"
      :api-params="apiParams" :checkbox="true" @selectTableChange="selectTableChange" :bordered="true">
      <template #price="{ data }">{{
        data.price
          ? unitPrice(data.price, '¥')
          : (data.couponDiscount || 0) + '折'
      }}</template>
      <template #publishNum="{ data }">
        {{ data.usedNum + "/" + data.receivedNum+"/" + (data.publishNum === 0 ? "不限制" : data.publishNum) }}
     </template>

      <template #time="{ data }">
        <div v-if="data?.getType === 'ACTIVITY' && data?.rangeDayType === 'DYNAMICTIME'">长期有效</div>
        <div v-else-if="data.startTime && data.endTime">{{ data.startTime }}<div style="margin: 0"></div>{{ data.endTime }}</div>
      </template>
      <template #edit="{ data }">
        <a-button @click="see(data)" style="margin-right: 10px;"
          v-if="data.promotionStatus == 'CLOSE' || data.promotionStatus == 'NEW'" type="text" status="warning">编辑</a-button>
        <a-button style="margin-right: 10px;" v-else @click="see(data, 'onlyView')" type="text" status="success">查看</a-button>
        <a-button @click="close(data)" style="margin-right: 10px;"
          v-if="data.promotionStatus == 'START' || data.promotionStatus == 'NEW'" type="text" status="danger">关闭</a-button>
        <a-button @click="remove(data)" style="margin-right: 10px;"
          v-if="data.promotionStatus == 'CLOSE' || data.promotionStatus == 'END'" type="text" status="danger">删除</a-button>
        <a-button  @click="receivePage(data)" style="margin: 5px" type="text">领取记录</a-button>
      </template>
    </PickTablePage>
  </a-card>
</template>

<script setup lang="ts">
import { deletePlatformCoupon, getShopCouponList, updatePlatformCouponStatus } from '@/api/promotion';
import { PickSearchColumn, PickTablePage } from '@pickmall/ui-v3-components';

import { ColumnsDataRule, MethodsRule, SearchRule } from '@/types/global';
import { useRouter } from 'vue-router';

import useCurrentInstance from '@/hooks/useCurrentInstance';
import { unitPrice } from '@/utils/filters';
import {
couponType,
promotionStatusSelect,
promotionsScopeTypeRender,
promotionsStatusRender
} from '@/utils/tools';
import { Message } from '@arco-design/web-vue';
import { ref, inject } from 'vue';


const reload: any = inject("reload");
const router = useRouter()
// 获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
const selectList = ref([]) // 接受子组件传过来的值
const tablePageRef = ref<any>();
const couponStatus = ref<string>('START')
const apiParams = ref<any>({ sort: 'startTime',promotionStatus:couponStatus.value });
const columnsSearch: Array<SearchRule> = [
  {
    label: '优惠券名称',
    model: 'couponName',
    disabled: false,
    input: true,
  },
  {
    label: '活动时间',
    model: 'selectDate',
    disabled: false,
    datePicker: {
      type: 'range',
    },
  },
];

const columnsTable: ColumnsDataRule[] = [
  {
    title: '活动名称',
    dataIndex: 'promotionName',
  },
  {
    title: '优惠券名称',
    dataIndex: 'couponName',
  },

  {
    title: '面额/折扣',
    dataIndex: 'price',
    slot: true,
    slotTemplate: 'price',
  },
  {
    title: '已使用/已领取/总数量',
    dataIndex: 'publishNum',
    slot: true,
    slotTemplate: 'publishNum',
  },
  {
    title: '优惠券类型',
    dataIndex: 'couponType',
    slot: true,
    slotData: {
      badge: couponType,
    },
  },
  {
    title: '品类描述',
    dataIndex: 'scopeType',
    slot: true,
    slotData: {
      badge: promotionsScopeTypeRender,
    },
  },
  {
    title: '活动时间',
    width: 180,
    ellipsis: false,
    dataIndex: 'startTime',
    slot: true,
    slotTemplate: 'time',
  },
  {
    title: '状态',
    dataIndex: 'promotionStatus',
    slot: true,
    slotData: {
      badge: promotionsStatusRender,
    },
  },
];

// todo 本页面操作列表为选择展示
const sortMethods: MethodsRule = {
  title: '操作',
  width: 280,
  methods: [
    {
      title: '编辑',
      slot: true,
      slotTemplate: 'edit'
    },
  ],
};
// 父组件传过来的数据
const selectTableChange = (val: any) => {
  if (val) {
    selectList.value = val
  }
}
// 批量关闭
const delAll = () => {
  console.log('selectList.value', selectList.value);
  if (selectList.value.length <= 0) {
    Message.error('您还未选择要下架的优惠券');
    return;
  }
  modal.confirm({
    title: '确认下架',
    content: `您确认要下架所选的${selectList.value.length}条数据?`,
    alignCenter: false,
    onOk: async () => {
      const ids = [] as any;
      selectList.value.forEach((item: any) => {
        ids.push(item.id);
      })
      const params = {
        couponIds: ids.toString(),
        promotionStatus: "CLOSE",
      };
      updatePlatformCouponStatus(params).then((res: any) => {
        if (res.data.success) {
          Message.success('下架成功');
          tablePageRef.value.init();
          // selectList.value = [];
          reload();
          console.log('selectList.value111', selectList.value);
        }
      })
    },
  });
}
// 查看
const add = (val: any) => {
  router.push({
    name: 'edit-platform-coupon',
  })
}
// 关闭
const close = (val: any) => {
  modal.confirm({
    title: '确认关闭',
    content: `确认要关闭此优惠券么?`,
    alignCenter: false,
    onOk: async () => {
      updatePlatformCouponStatus({
        couponIds: val.id,
        effectiveDays: 0,
      }).then((res: any) => {
        if (res.data.success) {
          Message.success('优惠券已关闭');
          tablePageRef.value.init();
        }
      })
    },
  });
}
// 删除
const remove = (val: any) => {
  modal.confirm({
    title: '确认删除',
    content: `确认要删除此优惠券么?`,
    alignCenter: false,
    onOk: async () => {
      deletePlatformCoupon(val.id).then((res: any) => {
        if (res.data.success) {
          Message.success('优惠券已关闭');
          tablePageRef.value.init();
        }
      })
    },
  });
}
// 查看/编辑
const see = (v: any, only?: any) => {
  let data;
  only ? data = { onlyView: 'true', id: v.id } : data = { id: v.id }
  router.push({  name: 'edit-platform-coupon', query: data })
}
// 优惠券领取记录
const receivePage = (val?: any) => {
  val.id ? router.push({ name: 'coupon-receive', query: { id: val.id } }) : router.push({ name: 'coupon-receive' })
}
</script>
